package com.ruoyi.workbench.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.WorkBenchConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.workbench.domain.WbContract;
import com.ruoyi.workbench.mapper.WbContractMapper;
import com.ruoyi.workbench.service.IWbContractService;
import com.ruoyi.workbench.utils.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 合同Service业务层处理
 *
 * @author ruoyi
 * @date 2020-10-10
 */
@Service("contractService")
public class WbContractServiceImpl implements IWbContractService {
    private final WbContractMapper wbContractMapper;

    public WbContractServiceImpl(WbContractMapper wbContractMapper) {
        this.wbContractMapper = wbContractMapper;
    }

    @Override
    public Map<Integer, List<WbContract>> selectExpireWbContractsMap() {
        WbContract wbContract = new WbContract();
        //设置未删除
        wbContract.setDelFlag("0");
        //设置处于存续状态的合同
        wbContract.setContractStatus(0);
        List<WbContract> contractList = selectWbContractList(wbContract);
        List<WbContract> contractList3 = new ArrayList<>();
        List<WbContract> contractList5 = new ArrayList<>();
        List<WbContract> contractList6 = new ArrayList<>();
        contractList.forEach(contract -> {
            //如果离上次提醒不足7天则不再提醒,否则提醒并且更新提醒日期
            Date lastNoticeDate = contract.getLastNoticeTime();
            if (!(Objects.isNull(lastNoticeDate) || DateUtil.isExpired(lastNoticeDate))) {
                return;
            } else {
                contract.setLastNoticeTime(new Date());
                updateWbContractNotice(contract);
            }
            int value = contract.getContractValue();
            Date endDate = contract.getContractEndDate();
            if (value <= WorkBenchConstants.VALUE_3000) {
                //价值3000以内提前3个月通知
                if (DateUtil.isExpiredByMonth(endDate, 3)) {
                    contractList3.add(contract);
                }
            } else if (value <= WorkBenchConstants.VALUE_10000) {
                //价值10000以内提前5个月通知
                if (DateUtil.isExpiredByMonth(endDate, 5)) {
                    contractList5.add(contract);
                }
            } else {
                //价值大于10000的提前6个月通知
                if (DateUtil.isExpiredByMonth(endDate, 6)) {
                    contractList6.add(contract);
                }
            }
        });
        Map<Integer, List<WbContract>> map = new HashMap<>(3);
        map.put(3, contractList3);
        map.put(5, contractList5);
        map.put(6, contractList6);
        return map;
    }

    public void updateWbContractNotice(WbContract wbContract) {
        wbContractMapper.updateWbContract(wbContract);
    }

    @Override
    public Integer selectWbContractStatusById(Long id) {
        return wbContractMapper.selectWbContractById(id).getContractStatus();
    }

    /**
     * 查询合同
     *
     * @param id 合同ID
     * @return 合同
     */
    @Override
    public WbContract selectWbContractById(Long id) {
        return wbContractMapper.selectWbContractById(id);
    }

    /**
     * 查询合同列表
     *
     * @param wbContract 合同
     * @return 合同
     */
    @Override
    @DataScope(deptAlias = "sd", userAlias = "su")
    public List<WbContract> selectWbContractList(WbContract wbContract) {
        return wbContractMapper.selectWbContractList(wbContract);
    }

    /**
     * 新增合同
     *
     * @param wbContract 合同
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertWbContract(WbContract wbContract) {

        SysUser currentUser = ShiroUtils.getSysUser();

        wbContract.setCreateTime(DateUtils.getNowDate());
        wbContract.setCreateBy(currentUser.getLoginName());
        return wbContractMapper.insertWbContract(wbContract);
    }

    /**
     * 修改合同
     *
     * @param wbContract 合同
     * @return 结果
     */
    @Override
    public int updateWbContract(WbContract wbContract) {
        SysUser currentUser = ShiroUtils.getSysUser();
        wbContract.setUpdateTime(DateUtils.getNowDate());
        wbContract.setUpdateBy(currentUser.getLoginName());
        return wbContractMapper.updateWbContract(wbContract);
    }

    /**
     * 删除合同对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteWbContractByIds(String ids) {
        return wbContractMapper.deleteWbContractByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除合同信息
     *
     * @param id 合同ID
     * @return 结果
     */
    @Override
    public int deleteWbContractById(Long id) {
        return wbContractMapper.deleteWbContractById(id);
    }

    @Override
    public String importUser(List<WbContract> contractList, String operateName) {
        if (Objects.isNull(contractList) || contractList.size() == 0) {
            throw new BusinessException("导入用户数据不能为空！");
        }
        AtomicInteger successNum = new AtomicInteger();
        AtomicInteger failureNum = new AtomicInteger();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        contractList.forEach(contract -> {
            if (StringUtils.isBlank(contract.getContractName())) {
                return;
            }
            int count = 0;
            //不符合格式的属性不准导入
            if (!(Objects.isNull(contract.getContractValue()) || Objects.isNull(contract.getContractStartDate()) || Objects.isNull(contract.getContractEndDate()))) {
                contract.setCreateBy(operateName);
                count = insertWbContract(contract);
            }
            if (count != 0) {
                successNum.getAndIncrement();
            } else {
                failureNum.getAndIncrement();
                failureMsg.append("<br/>").append(contract.getContractName()).append("导入失败");
            }
        });

        if (failureNum.get() > 0) {
            failureMsg.insert(0, "导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }
}
